﻿#region 文件信息

// FileName: SoCafeShop/Sohobloo.SoMcCoffee.Data/EfDbContext.cs
// Author: Sohobloo
// CreateTime: 2013/06/28 20:31
// UpdateTime: 2013/06/30 3:41

#endregion

#region 引用

using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Data.Entity;
using System.Data.Entity.ModelConfiguration.Conventions;

#endregion

namespace Sohobloo.SoMcCoffee.Data
{
    /// <summary>
    ///     EF数据访问上下文
    /// </summary>
    [Export(typeof (DbContext))]
    public class EfDbContext : DbContext
    {
        private const string ConnectionName = "DefaultConnection";

        public EfDbContext()
            : base(ConnectionName)
        {
        }

        public EfDbContext(string nameOrConnectionString)
            : base(nameOrConnectionString)
        {
        }

        [ImportMany]
        public IEnumerable<IEntityMapper> EntityMappers { get; set; }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            //移除复数表名
            modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
            //移除一对多的级联删除约定，想要级联删除可以在 EntityTypeConfiguration<TEntity>的实现类中进行控制
            //modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>();

            if (Configuration == null)
            {
                return;
            }
            foreach (var mapper in EntityMappers)
            {
                mapper.RegistTo(modelBuilder.Configurations);
            }
        }
    }
}